package com.fcl.mylibrary.banner;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ToxicBakery.viewpager.transforms.RotateDownTransformer;
import com.fcl.mylibrary.R;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by fang on 2016/8/26.
 */
public class MyPagerLayout extends RelativeLayout {
    /**
     * 配置项
     */
    private MyPagerConfig mMyPagerConfig;
    private Context mContext;
    /**
     * viewpager
     */
    private ViewPager mPager;
    /**
     * viewpager的适配器
     */
    private PagerAdapter mPagerAdapter;

    /**
     * 位于viewpager下方的圆圈
     */
    private LinearLayout mPointLayout;
    /**
     * 下方圆圈视图
     */
    private ImageView[] mPointImages;

    /**
     * 圆圈视图与底部的距离
     */
    private int POINT_BOTTOM_MARGIN = 10;

    /**
     * 圆圈视图与右边的距离
     */
    private int POINT_RIGHT_MARGIN = 10;

    /**
     * 圆圈之间间隔
     */
    private int POINT_SPACE = 5;

    /**
     * 圆圈大小
     */
    private int POINT_SIZE = 10;
    /**
     * 图片的数量
     */
    private int mImageNum;
    /**
     * 当前位置
     */
    private int mCurPos = 0;
    /**
     * 滑动时间间隔，默认5s
     */
    private int SCROLL_DURATION = 5000;
    private static final int AUTO_SCROLL = 0;
    private MyScroller mMyScroller;

    /**
     * 描述文本
     */
    private TextView mDescText;

    /**
     * 圆圈的位置
     */
    public enum PointPos {
        LEFT_BOTTOM,
        RIGHT_BOTTOM,
        CENTER_BOTTOM,
    }

    private List<String> mTextDatas = new ArrayList<>();

    /**
     * 圆圈默认在右
     */
    private PointPos mPointPos = PointPos.RIGHT_BOTTOM;
    /**
     * 文字默认在左
     */
    private PointPos mTextPos = PointPos.LEFT_BOTTOM;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AUTO_SCROLL:
                    if (mImageNum != 0) {
                        mCurPos = (mCurPos + 1) % mImageNum;
                        setCurrentItem(mCurPos);
                        setPoints(mCurPos);
                    }

                    mHandler.sendMessageDelayed(Message.obtain(), SCROLL_DURATION);
                    break;
            }
        }
    };

    public void setScrollDuration(int duration) {
        this.SCROLL_DURATION = duration;
    }

    public MyPagerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
init();
    }

    public void set(MyPagerConfig config) {
        this.mMyPagerConfig = config;
        init();
    }

    /**
     * 添加viewpager和底部的圆圈
     */
    private void init() {
        initPager();
        initPointLayout();
        initText();
        setParams();
    }

    private void setParams() {
        setBottom(mPointLayout, mPointPos);
        setBottom(mDescText, mTextPos);
    }

    private void setBottom(View view, PointPos pos) {
        LayoutParams linearParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        linearParams.bottomMargin = POINT_BOTTOM_MARGIN;
        linearParams.rightMargin = POINT_RIGHT_MARGIN;
        linearParams.leftMargin = POINT_RIGHT_MARGIN;
        int rule = RelativeLayout.CENTER_HORIZONTAL;
        switch (pos) {
            case LEFT_BOTTOM:
                rule = RelativeLayout.ALIGN_PARENT_LEFT;
                break;
            case RIGHT_BOTTOM:
                rule = RelativeLayout.ALIGN_PARENT_RIGHT;
                break;
        }
        linearParams.addRule(rule);
        linearParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        view.setLayoutParams(linearParams);
    }

    private void initText() {
        mDescText = new TextView(mContext);
        mDescText.setTextColor(Color.WHITE);
        addView(mDescText);
    }

    private void initPointLayout() {
        //设置圆圈位于底部，水平中间的位置
        mPointLayout = new LinearLayout(getContext());
        addView(mPointLayout);
    }

    /**
     * 自动滚动
     */
    public void startScroll() {
        mHandler.sendMessageDelayed(Message.obtain(mHandler, AUTO_SCROLL), SCROLL_DURATION);
    }

    /**
     * 设置圆圈的位置
     * @param mPointPos
     */
    public void setPointPos(PointPos mPointPos) {
        this.mPointPos = mPointPos;
        setParams();
    }

    public void setTextPos(PointPos pos) {
        this.mTextPos = pos;
        setParams();
    }

    public void setTextDatas(List<String> textDatas) {
        this.mTextDatas = textDatas;
    }

    public ViewPager getPager() {
        return mPager;
    }

    /**
     * 设置适配器
     * @param pagerAdapter
     */
    public void setPagerAdapter(PagerAdapter pagerAdapter) {
        this.mPagerAdapter = pagerAdapter;
        mPager.setAdapter(mPagerAdapter);
        mImageNum = mPagerAdapter.getCount();
    }

    public void setImageNum(int data) {
        this.mImageNum = data;
    }

    /**
     * ViewPager的初始化
     */
    private void initPager() {
        mPager = new ViewPager(getContext());

        mPager.setId(R.id.test);

        mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
setPoints(position);
//                mDescText.setText(mTextDatas.get(position));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mPager.setPageTransformer(true, new RotateDownTransformer()); //设置切换动画
        setPagerScroll();
        ViewGroup.LayoutParams pagerParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        addView(mPager, pagerParams);
    }

    /**
     * 设置自定义的Scroller，更改页面切换的时间
     */
    private void setPagerScroll() {
        try {
            Field mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            mMyScroller = new MyScroller(mContext);
            mScroller.set(mPager, mMyScroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置当前选中项
     * @param pos
     */
    public void setCurrentItem(int pos) {
        mPager.setCurrentItem(pos, true);
//        mDescText.setText(mTextDatas.get(pos));
    }



    /**
     * 根据图片数量设置圆圈
     */
    public void setPoints(int itemPos) {
        mPointLayout.removeAllViews();
        if (mImageNum > 0) {
            mPointImages = new ImageView[mImageNum];
            }
        for (int i = 0; i < mImageNum; i++) {
            ImageView imageView = new ImageView(getContext());
            mPointImages[i] = imageView;
            //当前pager显示页对应的圆圈是不一样的
            if (i == itemPos) {
                mPointImages[i]
                        .setBackgroundResource(R.drawable.page_indicator_focused);
            } else {
                mPointImages[i]
                        .setBackgroundResource(R.drawable.page_indicator_unfocused);
            }
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    new ViewGroup.LayoutParams((int) dp2px(POINT_SIZE), (int) dp2px(POINT_SIZE)));
            layoutParams.leftMargin = POINT_SPACE;
            layoutParams.rightMargin = POINT_SPACE;
            mPointLayout.addView(imageView, layoutParams);
        }
    }

    public  float dp2px(float dp) {
        return dp * getDisplayMetrics().density;
    }

    public  float px2dp(float px) {
        return px / getDisplayMetrics().density;
    }

    public  DisplayMetrics getDisplayMetrics() {
        return mContext.getResources().getDisplayMetrics();
    }
}
